package cn.tedu.bigdecimal;
/**
 * @Author 金帮嘉诚  @Date 2021-06-16 周三 20:49
 */
/*本类用于解决浮点数运算不精确的问题*/

import java.math.BigDecimal;
import java.util.Scanner;

/**
 * 知识点：
 * BigDecimal的add()   subtract()    multiply()    divide()方法
 * 注意点1：接受数字用double，但BigDecimal用String类型赋值
 * 注意点2：divide设置保留位数和舍入规则
 */
public class TestBigDecimal {
    public static void main(String[] args) {
        f1();
        f2();

    }

    private static void f1() {
        System.out.println("请输入要计算的两个数字");
        double a = new Scanner(System.in).nextDouble();
        double b = new Scanner(System.in).nextDouble();

        System.out.println("(a+b) = " + (a + b));
        System.out.println("(a-b) = " + (a - b));
        System.out.println("(a*b) = " + (a * b));
        System.out.println("(a/b) = " + (a / b));
    }

    private static void f2() {
        System.out.println("请输入要计算的两个数字");
        double a = new Scanner(System.in).nextDouble();
        double b = new Scanner(System.in).nextDouble();

        /*注意此处要用String参数赋值，用double赋值会有误差*/
        BigDecimal bd1 = new BigDecimal(a + "");
        BigDecimal bd2 = new BigDecimal(b + "");

        System.out.println("bd1.add(bd2) = " + bd1.add(bd2));
        System.out.println("bd1.subtract(bd2) = " + bd1.subtract(bd2));
        System.out.println("bd1.multiply(bd2) = " + bd1.multiply(bd2));
        /*divide会出现除不尽的情况，因此要提前设置保留位数和舍入规则*/
        System.out.println("bd1.divide(bd2,3,BigDecimal.ROUND_HALF_UP) = " + bd1.divide(bd2, 3, BigDecimal.ROUND_HALF_UP));
    }
}
